package main

import (
	"fmt"
	"io"
	"net/http"
	"os"

	//	"runtime"
	"strconv"
)

func httpGet(url string) (result string, err error) {

	resp, err1 := http.Get(url)
	if err1 != nil {
		err = err1
	}
	defer resp.Body.Close()

	buf := make([]byte, 4096)
	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			//fmt.Println("读取结束")
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		result += string(buf[:n])
	}
	return
}

func SpiderPage(i int, page chan int) {
	url := "https://tieba.baidu.com/f?kw=xboxone&ie=utf-8&pn=" + strconv.Itoa((i-1)*50)

	result, err := httpGet(url)
	if err != nil {
		fmt.Println("获取错误:", err)
		return
	}

	f, err := os.Create("./result" + strconv.Itoa(i) + ".html")

	if err != nil {
		fmt.Print("文件创建错误", err)
		return
	}

	f.WriteString(result)
	f.Close()
	page <- i
}

func working(start, end int) {
	page := make(chan int)
	fmt.Printf("正在获取第%d页到第%d页:", start, end)
	for i := start; i <= end; i++ {
		go SpiderPage(i, page)
	}
	for i := start; i <= end; i++ {
		fmt.Println("第" + strconv.Itoa(<-page) + "页已获取")
	}
}
func main() {

	var start, end int
	fmt.Println("请输入起始页:")
	fmt.Scan(&start)
	fmt.Println("请输入终止页:")
	fmt.Scan(&end)

	working(start, end)

}
